using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web;

namespace Configuracion
{
    public class ConfigManager
    {
        #region Metodos

        private static Configuration GetConfiguration()
        {
            string path;
            Configuration config;

            if (HttpContext.Current == null)
            {
                path = System.IO.Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    AppDomain.CurrentDomain.FriendlyName);

                config = ConfigurationManager.OpenExeConfiguration(path);
            }
            else
            {
                path = HttpContext.Current.Request.ApplicationPath;

                config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(path);
            }

            return config;
        }

        public static string GetValue(string key)
        {
            Configuration config;
            string value;

            try
            {
                config = GetConfiguration();

                try
                {
                    value = config.AppSettings.Settings[key].Value;
                }
                catch(Exception ex)
                {
                    throw new Exception(
                        String.Format("Error: la clave '{0}' no existe en el archivo de configuracion.", key), ex);
                }
                return value;
            }
            finally
            {
                config = null;
            }
        }
        
        #endregion

    }
}
